<?php
/**
 * Created by PhpStorm.
 * User: Vagrant Archer
 * Date: 2017/8/7
 * Time: 17:37
 */

use yii\db\Connection;
use yii\db\Query;
use yii\di\Instance;

class Universe
{
	private	$universeName		=	'';
	private $universeNo			=	null;
	private $galaxies 			= 	array();
	private $historiographers	=	array();

	private  $db		 		= 	'dbHeimdall';

	public function create(int $inputUniverseNo)
	{
		/** 建立数据库示例 */
		$this->db = Instance::ensure($this->db, Connection::className());

		$this->createUniverse($inputUniverseNo);
		$this->createHistoriographers();
		$this->createGalaxies();
	}


	/** 建立Universe */
	public function createUniverse(int $inputUniverseNo)
	{
		$command = $this->db->createCommand("SELECT * FROM universe WHERE universeNo =  :universeID")->bindValue(':universeID', $inputUniverseNo);
		$query = $command->queryAll();
		if (0 == sizeof($query)) {
			throwException(NoSuchUniverse);
		}
		$this->universeNo	=	$inputUniverseNo;
		$this->universeName =	$query[0]['universeName'];
	}

	/**  建立Galaxy */
	public function createGalaxies()
	{
		$command = $this->db->createCommand("SELECT * FROM galaxy WHERE galaxy.universeNo =  {$this->universeNo}");
		$query	 = $command -> queryAll();
		foreach ($query as $inGalaxy) {
			$galaxy = new Galaxy();
			$galaxy->create($inGalaxy, $this->historiographers);
			array_push($this->galaxies, $galaxy);
		}
	}

	/** 建立记录器 */
	public function createHistoriographers()
	{
		$command = $this->db->createCommand("SELECT hgType, hgToken FROM historiographer WHERE hgNo IN (SELECT historiographerNo FROM universehistoriographer WHERE universeNo = {$this->universeNo})");
		$query	 = $command -> queryAll();
		foreach ($query as $item) {
			array_push($this->historiographers, HistoriographerFactory::createHistoriographer($item['hgType'], $item['hgToken']));
		}
	}

	public function stare()
	{
		foreach ($this->galaxies as $galaxy) {
			$galaxy->stare();
		}
	}
}